import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {finalize, tap} from 'rxjs/operators';

/**
 *  请求日志拦截器，主要记录请求花费时间、状态等
 */
@Injectable()
export class LogInterceptor implements HttpInterceptor {

  constructor() {
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const startTime = Date.now();
    let status: string;

    return next.handle(request).pipe(tap(event => {
        status = '';
        if (event instanceof HttpResponse) {
          status = 'succeeded';
        }
      }, error => status = 'failed'),
      finalize(() => {
        const elapsedTime = Date.now() - startTime;
        const message = request.method + ' ' + request.urlWithParams + ' ' + status + ' in ' + elapsedTime + 'ms';
        console.log(message);
      })
    );
  }
}
